package com.example.demo.LeetCode.string;


import java.util.HashMap;
import java.util.Map;

public class LengthOfLongestSubStr {
    // abcabc123

    /**
     * 滑动窗口
     * @param
     * @return
     */
    public static  int lengthOfLongestSubstring(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max = 0;
        int left = 0;
        for(int i = 0; i < s.length(); i ++){
            if(map.containsKey(s.charAt(i))){
                left = Math.max(left,map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i),i);
            // 子字符串头尾距离，长度，窗口长度
            max = Math.max(max,i-left+1);
        }
        return max;
    }

    public static  void test(String str){
        int size = str.length();
        Map<Character,Integer> map = new HashMap<>(size);
        int max = 0;
        int left = 0 ;
        for (int i= 0; i< size;i++){
            if (map.containsKey(str.charAt(i))){
                //滑动
                left = Math.max(left,map.get(str.charAt(i))+1);
            }
            map.put(str.charAt(i),i);
            max = Math.max(max,i-left+1);
        }

    }

    public static void main(String[] args) {
        String str = "abcabc123";
        System.out.println(lengthOfLongestSubstring(str));
    }
}
